<?php

/**
 * Name: 签到记录仓储层
 * User: Silent
 * Date: 2025-11-07
 * Time: 15:30:00
 */

namespace App\Repositories\Checkin;

use App\Models\Checkin\SignInRecord;
use App\Repositories\BaseRepository;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;

class SignInRecordRepository extends BaseRepository
{
    public function __construct(SignInRecord $model)
    {
        parent::__construct($model);
    }

    /**
     * 创建或更新记录
     */
    public function updateOrCreate(array $attributes, array $values = [])
    {
        return $this->model->updateOrCreate($attributes, $values);
    }

    /**
     * 检查员工今天是否已经签到
     */
    public function hasSignedToday($employeeId, $date = null)
    {
        $date = $date ?: today();

        return $this->query()
            ->where('employee_id', $employeeId)
            ->where('sign_date', $date)
            ->exists();
    }

    /**
     * 获取员工的签到记录
     */
    public function getEmployeeSignRecord($employeeId, $date)
    {
        return $this->query()
            ->where('employee_id', $employeeId)
            ->where('sign_date', $date)
            ->first();
    }

    /**
     * 获取指定日期班组的签到记录
     */
    public function getTeamSignRecords($teamName, $date)
    {
        return $this->query()
            ->where('team_name', $teamName)
            ->where('sign_date', $date)
            ->orderByRaw("FIELD(status, 'abnormal', 'normal')")
            ->orderBy('sign_time')
            ->get();
    }

    /**
     * 获取员工的签到日历数据
     */
    public function getEmployeeCalendar($employeeId, $year, $month)
    {
        $startDate = Carbon::createFromDate($year, $month, 1)->startOfMonth();
        $endDate = $startDate->copy()->endOfMonth();

        return $this->query()
            ->where('employee_id', $employeeId)
            ->whereBetween('sign_date', [$startDate, $endDate])
            ->get()
            ->keyBy(function($item) {
                return $item->sign_date->format('Y-m-d');
            });
    }

    /**
     * 获取指定日期所有班组的签到统计
     */
    public function getDailySignStatistics($date)
    {
        return $this->query()
            ->where('sign_date', $date)
            ->selectRaw('team_name, status, COUNT(*) as count')
            ->groupBy('team_name', 'status')
            ->get()
            ->groupBy('team_name');
    }

    /**
     * 获取异常签到记录
     */
    public function getAbnormalSignRecords($date, $teamName = null)
    {
        $query = $this->query()
            ->where('sign_date', $date)
            ->where('status', SignInRecord::STATUS_ABNORMAL);

        if ($teamName) {
            $query->where('team_name', $teamName);
        }

        return $query->get();
    }

    /**
     * 创建签到记录
     */
    public function createSignRecord($employeeData, $signData)
    {
        // 先创建基础记录数据（暂时状态设为 normal）
        $recordData = array_merge($signData, [
            'employee_id' => $employeeData['id'],
            'employee_name' => $employeeData['username'],
            'team_name' => $signData['team_name'] ?? $employeeData['team'] ?? null,  // 优先使用提交的team_name，否则使用员工的team
            'sign_date' => today(),
            'sign_time' => now(),
            'status' => SignInRecord::STATUS_NORMAL  // 临时状态
        ]);

        // 创建记录
        $record = $this->create($recordData);

        // 根据记录判断是否异常并更新状态
        if ($record->isAbnormal()) {
            // 收集异常项信息
            $abnormalItems = $record->collectAbnormalItems();
            
            // 更新状态和异常描述
            $record->update([
                'status' => SignInRecord::STATUS_ABNORMAL,
                'abnormal_desc' => $abnormalItems
            ]);
        }

        return $record;
    }

    /**
     * 获取员工签到记录列表（分页）
     */
    public function getEmployeeSignRecords($employeeId, $perPage = 15)
    {
        return $this->query()
            ->where('employee_id', $employeeId)
            ->orderBy('sign_date', 'desc')
            ->paginate($perPage);
    }

    /**
     * 获取班组签到记录列表（分页）
     */
    public function getTeamSignRecordsPaginated($teamName, $perPage = 15, $filters = [])
    {
        $query = $this->query()->where('team_name', $teamName);

        // 日期筛选
        if (isset($filters['start_date'])) {
            $query->where('sign_date', '>=', $filters['start_date']);
        }
        if (isset($filters['end_date'])) {
            $query->where('sign_date', '<=', $filters['end_date']);
        }

        // 状态筛选
        if (isset($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        return $query->orderBy('sign_date', 'desc')
                    ->orderBy('sign_time', 'desc')
                    ->paginate($perPage);
    }

    /**
     * 获取所有班组的签到记录（主管用）
     */
    public function getAllTeamsSignRecords($date, $teams = null)
    {
        $query = $this->query()->where('sign_date', $date);

        if ($teams && is_array($teams)) {
            $query->whereIn('team_name', $teams);
        }

        return $query->orderByRaw("FIELD(status, 'abnormal', 'normal')")
                    ->orderBy('team_name')
                    ->orderBy('sign_time')
                    ->get()
                    ->groupBy('team_name');
    }
}

